package com.jeecg.demo.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.ListView;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.common.IOUtil;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.core.util.IpUtil;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.PasswordUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.jwt.def.JwtConstants;
import org.jeecgframework.jwt.service.TokenManager;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.web.system.service.SystemService;
import org.jsoup.Connection.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriComponentsBuilder;
import net.sf.json.JSONArray;

import com.jeecg.demo.entity.App_User;
import com.jeecg.demo.entity.Infomation;
import com.jeecg.demo.entity.AdInfo;
import com.sun.star.i18n.reservedWords;

/**
 * @Title: Controller
 * @Description: 客户端用户登注册录接口
 * @author onlineGenerator
 * @date 2018-08-23 14:58:22
 * @version V1.0
 * 
 */
@Api(value = "getAppDate", description = "app信息获取", tags = "getAppDate")
@Controller
@RequestMapping("/getAppDate")
public class GetAppDate {
	private static final Logger logger = LoggerFactory.getLogger(GetAppDate.class);

	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private TokenManager tokenManager;
	
//	private String url=ResourceUtil.getConfigByName("url");//url具体根据条件获取
//	private String url_out=ResourceUtil.getConfigByName("url_out");//url_out具体根据条件获取
//	/*static String head=ConfigTool.getProConfig("server.file");*/
//	private static String head=ResourceUtil.getConfigByName("server.file");
	private String url=null;
	private String url_out=null;
	private static String head=null;
	/**
	 * 获取信息
	 * 
	 * @param phoneNum
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "/getdate", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "getinformation", produces = "application/json", httpMethod = "POST")
	public ResponseMessage<?> getdate(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required=false) String getinfo,
			@RequestParam(required=false) String method,
			@RequestParam(required=false) String type,
			@RequestParam(required=false) String id
			) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		/*if (StringUtils.isNotBlank(getinfo)) {
			if ("upload".equals(getinfo)) {
				request.getRequestDispatcher("upload.action").forward(request,
						response);
			} else {
				request.getRequestDispatcher("coalMall.action").forward(
						request, response);
			}
		}*/
		
		if ("getLoadingPage".equals(method)) {//home page lodd bingo
			int flag = -1;
			String msg = "";
			int loadid=-1;
			String path="";
			String sql = "select APP_LOADING_ID,PIC_PATH  from app_loading where ISVAILD=1";
			List<Map<String, Object>> listMap = systemService
					.findForJdbc(sql, null);
			if (listMap.size()>0) {
				Map<String, Object> map = listMap.get(0);
				loadid = Integer.parseInt(map.get("APP_LOADING_ID").toString());
				path =(String)map.get("PIC_PATH");
				if(path !=null){
					if(path.indexOf("http://")<0){
						path=url+path.replace('\\', '/');
					}
				}
				msg="获取成功";
			}else{
				flag=0;
				msg="获取失败";
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", flag);
			jsonObject.put("type", "getLoadingPage");
			jsonObject.put("msg", msg);
			jsonObject.put("path", path);
			jsonObject.put("loadid", loadid);
			return Result.success(jsonObject);
		} else if ("AdManager".equals(method)) {//ad rotation  bingo
			int flag = -1;
			String msg = "";
			int loadid=-1;
			String path="";
			String sql="select i.* from app_ad_info i inner join app_ad_space s on i.adspace_id = s.adspace_id "
					+"where i.sysid in (select max(i.sysid) from app_ad_info i where i.status =1 and i.ad_area_id=? group by i.adspace_id)"
					+" order by s.ordernum asc";
			List<Map<String, Object>> listMap = systemService
					.findForJdbc(sql, type);
			JSONObject jsonObject = new JSONObject();
			List<AdInfo> list =new ArrayList<AdInfo>();
			if (listMap.size()>0) {
				for (int i = 0; i < listMap.size(); i++) {
					flag =1;
					AdInfo ad=new AdInfo();
					Map<String, Object> map = listMap.get(i);
					ad.setAd_area_id(type);
					ad.setAd_info_id(Integer.parseInt(map.get("ad_info_id").toString()));
					ad.setAd_info_id(Integer.parseInt(map.get("adspace_id").toString()));
					path=(String)map.get("pic_path");
					if(path !=null){
						if(path.indexOf("http://")<0){
							path=url+path.replace('\\', '/');
						}
					}
					ad.setPic_path(path);
					ad.setTitle((String)map.get("title"));
					ad.setIsnull_content((String)map.get("isnull_content"));
					list.add(ad);
				}
				msg = "获取成功";
			}else{
				flag=0;
				msg="获取失败";
			}
			jsonObject.put("status", flag);
			jsonObject.put("type", "getAdspace");
			jsonObject.put("msg", msg);
			if (list.size() > 0) {
				JSONArray jsonArray = JSONArray.fromObject(list);
				jsonObject.put("data", jsonArray.toArray());
			} else {
				jsonObject.put("data", "");
			}
			return Result.success(jsonObject.toString());
		}else if ("getLunbo".equals(method)) {//get rotation information  bingo
			String sql="select * from app_information where info_type_id=2" 
					+" and STATUS=1 and CAROUSEL=1 and rownum<=5 order by CAROUSEL_ORDER asc,create_date asc";
			List<Map<String, Object>> listMap = systemService
					.findForJdbc(sql, null);
			List<Infomation> list = new ArrayList<Infomation>();
			for (int i = 0; i < listMap.size(); i++) {
				Map<String, Object> map = listMap.get(i);
				Infomation info = new Infomation();
				info.setNewsId(Integer.parseInt(map.get("INFO_ID").toString()));
				info.setNewsPic(url_out + map.get("PIC_PATH").toString());
				info.setNewsTitle(map.get("TITLE").toString());
				list.add(info);
			}
			if (list.size()>0) {
				JSONArray jsonArray = JSONArray.fromObject(list);
				return Result.success(jsonArray.toString());
			}
		}else if ("getZXLunbo".equals(method)) {//get center rotation information  bingo
			String sql = " select * from app_information where info_type_id=? "
					+" and STATUS=1 and CAROUSEL=1 and rownum<=5 order by CAROUSEL_ORDER asc,create_date asc";
			List<Map<String, Object>> listMap = systemService
					.findForJdbc(sql,type);
				List<Infomation> list = new ArrayList<Infomation>();
			for (int i = 0; i < listMap.size(); i++) {
				Map<String, Object> map = listMap.get(i);
				Infomation info = new Infomation();
				info.setNewsId(Integer.parseInt(map.get("INFO_ID").toString()));
				info.setNewsPic(url + map.get("PIC_PATH").toString());
				info.setNewsTitle(map.get("TITLE").toString());
				list.add(info);
			}
			if (list.size()>0) {
				JSONArray jsonArray = JSONArray.fromObject(list);
				return Result.success(jsonArray.toString());
			}
		}
		else if ("getListData".equals(method)){//get information list  bingo
			String page=request.getParameter("page");
			if ("".equals(page)) {
				page="1";
			}
			int begin = (Integer.parseInt(page) - 1) * 10;
			int end = 10*Integer.parseInt(page);
			String sql = "select * from (SELECT A.*, ROWNUM RN from ("
					+ " select * from (select *  from app_information where info_type_id= ? and STATUS=1  and  set_top=1 and  subject_code is null order by create_date desc) t union all"
					+ " select * from (select *  from app_information where  info_type_id= ? and STATUS=1 and  set_top=0  and  subject_code is null order by create_date desc)t1"
					+ ") A WHERE ROWNUM <= ?) WHERE RN > ?";
			List<Map<String, Object>> listMap = systemService
					.findForJdbc(sql,type,type,end,begin);
			List<Infomation> list = new ArrayList<Infomation>();
			for (int i = 0; i < listMap.size(); i++) {
				Map<String, Object> map = listMap.get(i);
				Infomation info = new Infomation();
				info.setNewsId(this.oToI(map.get("INFO_ID")));
				//info.setNewsPic(url + rs.get("PIC_PATH"));
				String path=this.oToS(map.get("PIC_PATH"));
				if(path !=null){
					if(path.indexOf("http://")<0){
						path=url+path.replace('\\', '/');
					}
				}
				info.setNewsPic(path);
				info.setNewsTitle(this.oToS(map.get("TITLE")).replace("\"", "”"));				
				info.setNewsDate(this.oToS(map.get("CREATE_DATE")).substring(0,10));
				info.setNewsSource(this.oToS(map.get("SOURCE")));
				info.setReadCount(this.oToI(map.get("READ_COUNT")));
				info.setScCount(this.oToI(map.get("COLLECTION_NUM")));
				info.setIsSubject(this.oToS(map.get("IS_SUBJECT")));
				info.setSubjectCode(this.oToI(map.get("SUBJECT_CODE")));
				info.setIsBigPhonto(this.oToS(map.get("IS_BIG_PHOTO")));
				info.setIsPictbrow(this.oToS(map.get("IS_PICTBROW")));
				list.add(info);
			}
			if (list.size()>0) {
				JSONArray jsonArray = JSONArray.fromObject(list);
				return Result.success(jsonArray.toString());		
			}
		}else if ("getZXContent".equals(method)) {//ad detail bingo
			String sql="select a.* ,b.*  from app_information a ,app_info_content b  " +
					"where a.info_id=b.info_id and  a.INFO_ID=?";
			List<Map<String, Object>> listMap = systemService
					.findForJdbc(sql,oToI(id));
			List<Infomation> list = new ArrayList<Infomation>();
			String content = null;
			for (int i = 0; i < listMap.size(); i++) {
				Map<String, Object> map = listMap.get(0);
				Infomation info = new Infomation();
				info.setNewsId(this.oToI(map.get("INFO_ID")));
				info.setNewsTitle(this.oToS(map.get("TITLE")));
				info.setNewsDate(this.oToS(map.get("CREATE_DATE")).substring(0,10));
				info.setNewsSource(this.oToS(map.get("SOURCE")));     
				info.setNewsContent(content);
				content = this.checkAndUpdate(this.oToS(map.get("content")));
				list.add(info);
			}
			if (list.size() > 0) {
				String updatesql="update app_information set READ_COUNT=READ_COUNT+1 where INFO_ID='"+id+"'";
				systemService.updateBySqlString(updatesql);
				JSONArray jsonArray = JSONArray.fromObject(list);
				return Result.success(jsonArray.toString());	
			}
		}else if ("updateAdReadcount".equals(method)) {//bingo 
			String updatesql = "update APP_AD_INFO set READ_COUNT=READ_COUNT+1 where ad_info_id='"+id+"'";
			int result = -1; 
			result = systemService.updateBySqlString(updatesql);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", result);
			jsonObject.put("type", type);
			jsonObject.put("msg", "");
			jsonObject.put("data", "");
			return Result.success(jsonObject.toString());	
		}else if ("ShareContent".equals(method)) {//重定向？？？
			
		}else if ("ShareAdContent".equals(method)) {//重定向？？？
			
		}else if ("regist_1".equals(method)) {//regist  bingo
			float result =-1;
			String phone = request.getParameter("phone");
			String password = request.getParameter("password");
			String proVince = request.getParameter("proVince");
			String city = request.getParameter("city");
			city = StringUtils.isNotEmpty(city) ? city : proVince;
			String username = request.getParameter("username");
			String workspace = request.getParameter("workspace");
			String usertype = request.getParameter("usertype");
			Session session = systemService.getSession();//get jdbc session 
			//ps.by this way get the session class from hibernatejdbc.
			//Want more detail.See GenericBaseCommonDao.java
			CallableStatement procCall;
			try {
				procCall = SessionFactoryUtils.getDataSource(session.getSessionFactory()).getConnection().prepareCall("{call app_userregister2(?,?,?,?,?,?)}");
				procCall.setString(1,phone);
				procCall.setString(2,city);
				procCall.setString(3,username);
				procCall.setString(4,password);
				procCall.setString(5,workspace);
				procCall.registerOutParameter(6, java.sql.Types.FLOAT);
				procCall.executeUpdate(); 
				float userId = procCall.getFloat(6); 
				result=userId;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				session.close();
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", result);
			jsonObject.put("type", "regist_1");
			jsonObject.put("msg", result > 0 ? "注册成功" : "注册失败");
			jsonObject.put("data", "");
			return Result.success(jsonObject.toString());	
		}
		else if ("regist_wx".equals(method)) {//regist by WeChat 暂时不用
			String openId = request.getParameter("openid");
			String username = request.getParameter("username");
			
			
		}else if ("SendMS".equals(method)) {//sent message check 缺短信接口
			String phone = request.getParameter("phone");
//			String callbackstr = GetMSgByInterface.requestSendMsg(phone);//sent message check phone||method not finish
			String callbackstr = null;
			String send_state = callbackstr.split(" ")[0];
			String code = "";
			if (send_state.equals("0")) {
				code = callbackstr.split(" ")[2];
			} else {
				code = "-1";
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", send_state);
			jsonObject.put("type", "sendmsg");
			jsonObject.put("msg", callbackstr.split(" ")[1]);
			jsonObject.put("data", 10 + "&" + code);
			logger.info("SendMS--------" + jsonObject.toString());
			return Result.success(jsonObject.toString());	
		}else if ("getUserInfo".equals(method)) {//get user info  bingo
			String userid = request.getParameter("userid");
			if (userid != null) {
				String 	sql= " select t.userid,t.LOGINNAME,t.mobile,t.SEX,t.username,dict.dicname usertype, t.usertype usertypevalue,"
						+" t.OPENID,t.TRADERID,t.TRADERNAME,t.REGIONCODE,s.regionname as city,a.regionname as province " 
						+" from V_ECP_USER t,SYS_APP_REGION s,SYS_APP_REGION a ,sys_dict dict "
                        +"where t.regioncode=s.regioncode and a.regioncode=s.parentcode and t.industryid=dict.diccode and dict.dictype='REGISTERTYPE' and t.userid=? ";
				List<Map<String, Object>> listMap = systemService
						.findForJdbc(sql,userid);
				List<App_User> list = new ArrayList<App_User>();
				if (listMap.size()>0) {
					Map<String, Object> map = listMap.get(0);
					App_User user = new App_User();
					user.setAPP_USER_ID(this.oToS(map.get("userid")));
					user.setCITY(this.oToS(map.get("city")));
					user.setNICKNAME(this.oToS(map.get("LOGINNAME")));
					user.setPROVINCE(this.oToS(map.get("province")));
					user.setSEX(this.oToS(map.get("SEX")));
					user.setPHONE_NUM(this.oToS(map.get("mobile")));
	                user.setTradername(this.oToS(map.get("TRADERNAME")));
	                user.setRegioncode(this.oToS(map.get("REGIONCODE")));
	                user.setUsername(this.oToS(map.get("username")));
	                user.setUsertype(this.oToS(map.get("usertype")));
	                user.setOpenId(this.oToS(map.get("OPENID")));
	                user.setUsertypevalue(this.oToS(map.get("usertypevalue")));
					list.add(user);
				}
				if (list.size() > 0) {
					JSONArray jsonArray = JSONArray.fromObject(list);
					return Result.success(jsonArray.toString());	
				}
			}
		}else if ("updateUser_1".equals(method)) {
			float result= -1;
			String unit = request.getParameter("unit");
			String username = request.getParameter("username");
			String regioncode = request.getParameter("regioncode");
			String loginname = request.getParameter("loginname");
			String userid = request.getParameter("userid");
			String usertype = request.getParameter("usertype");
			Session session = systemService.getSession();
			CallableStatement procCall;
//			try {
//				procCall = SessionFactoryUtils.getDataSource(session.getSessionFactory()).getConnection().prepareCall("{call app_userregister2(?,?,?,?,?,?)}");
//				procCall.setString(1,phone);
//				procCall.setString(2,city);
//				procCall.setString(3,username);
//				procCall.setString(4,password);
//				procCall.setString(5,workspace);
//				procCall.registerOutParameter(6, java.sql.Types.FLOAT);
//				procCall.executeUpdate(); 
//				float userId = procCall.getFloat(6); 
//				result=userId;
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}finally{
//				session.close();
//			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", result);
			jsonObject.put("type", "regist_1");
			jsonObject.put("msg", result > 0 ? "注册成功" : "注册失败");
			jsonObject.put("data", "");
			return Result.success(jsonObject.toString());	
		}else if ("updatePwd".equals(method)) {//change password
			String phone = request.getParameter("phone");
			String password = request.getParameter("password");
			String 	updatesql= "update  sys_user set password='"+password+"' where loginname='"+phone+"'";
			
			int updateBySqlString = systemService.updateBySqlString(updatesql);
//			logger.info("updatePwd--------" + jsonstr);
//			out.write(jsonstr);
		} 
		
		return Result.error("Sorry,but there is no result for you.Pls check the request again");
	}
	
	
	
	private static String checkAndUpdate(String str) {
		str=str.replaceAll("font-size:16px;", "font-size:1.2em;");
		String url="";
		if(str !=null){
			String[] result = str.split("<img");
			url = result[0];
			for(int i=1;i<result.length;i++){
				StringBuffer sb = new StringBuffer("<img" + result[i]);
				if (!sb.toString().contains("http://")) {//without http
					int startAt = sb.indexOf("src", 1) + 5;
					int dirStartAt = sb.indexOf("/upload", 1);
					if(startAt < dirStartAt){
						sb.replace(startAt, dirStartAt, "");
					}
					StringBuffer sb2 = sb.insert(startAt, head);
					url = url + sb2.toString();
				}else{//exist
					url = url + sb.toString();
					continue;
				}
			}
		}
		return url;
	}
	
	private String oToS(Object object){//tool change object to String 
		if (object==null) {
			return "";
		}
		return object.toString();
	}
	
	private int oToI(Object object){//tool change object to interger
		if (object==null) {
			return -1;
		}
		int myInt = Integer.parseInt(object.toString());
		return myInt;
	}
}
